------------------------------------------------------------------------------
-- Utility library for computercraft's turtles by Hea3veN
-- Version 0.1
------------------------------------------------------------------------------
-- Example:
--
--     loadfile("turtle_utils.lua")()
--
--     forward(5)
--     turtle.turnRight()
--     turtle.turnRight()
--     forward(5)
--     down(2)
--
-- Interface:
--
--     fuelFor(movement)
--        Checks if turtle has enough fuel to move *movement* number of times.
--        If it does not, it tries to refuel from the first slot until it has
--        enough.
--
--     dig()
--     digUp()
--     digDown()
--        Digs the block in front/up/down of the turtle until there is only
--        air left. It returns false if it could not dig any more(which is a 
--	      sign of bedrock), otherwise returns true.
--
--     forward(num)
--     up(num)
--     down(num)
--        Moves the turtle forward/up/down *num* number of times, digging up
--        all the blocks that are in it's way. It returns false if it could
--        not move any more(which is a sign of bedrock), otherwise returns
--        true.
--


function fuelFor(movement)
	if turtle.getFuelLevel() <= (movement + 1) then
		turtle.select(1)
		print("Refuelling")
		while turtle.getFuelLevel() <= (movement + 1) do
			turtle.refuel(1)
			os.sleep(0.5)
		end
	end
	return true
end

function dig()
	while turtle.detect() do
		if not turtle.dig() then 
			return false
		end
		os.sleep(0.5)
	end
	return true
end

function digDown()
	while turtle.detectDown() do
		if not turtle.digDown() then 
			return false
		end
		os.sleep(0.5)
	end
	return true
end

function digUp()
	while turtle.detectUp() do
		if not turtle.digUp() then 
			return false
		end
		os.sleep(0.5)
	end
	return true
end

function forward(num)
	fuelFor(num)
	for i=1,num do
		local moved = false
		while not moved do
			if not dig() then
				return false
			end
			if turtle.forward() then
				moved = true
			else
				while turtle.attack() do
					os.sleep(0.5)
				end
			end
		end
	end
	return true
end

function up(num)
	fuelFor(num)
	for i=1,num do
		local moved = false
		while not moved do
			if not digUp() then
				return false
			end
			if turtle.up() then
				moved = true
			else
				while turtle.attack() do
					os.sleep(0.5)
				end
			end
		end
	end
	return true
end

function down(num)
	fuelFor(num)
	for i=1,num do
		local moved = false
		while not moved do
			if not digDown() then
				return false
			end
			if turtle.down() then
				moved = true
			else
				while turtle.attack() do
					os.sleep(0.5)
				end
			end
		end
	end
	return true
end

